package com.hbter630.change.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbter630.change.DTO.UserDTO;
import com.hbter630.change.entity.User;
import com.hbter630.change.mapper.UserMapper;
import com.hbter630.change.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbter630.change.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xbfinal
 * @since 2023-05-24
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result login(User user , HttpServletRequest request) {

        if(user==null || user.getPassword().equals("")){
            return Result.failed("请输入密码");
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email",user.getEmail());
        //查数据库

        User user1 = baseMapper.selectOne(userQueryWrapper);

        log.info("当前user：{}",user1);
        if(BeanUtil.isEmpty(user1)){
            //为空则返回登录失败
            return Result.failed("邮件错误");

        }
//        md5加密
        String psd = user.getPassword();
        String password = SecureUtil.md5(psd);

        if(!password.equals(user1.getPassword())){
            return Result.failed("密码错误");
        }
        String requestURI = request.getRequestURI();

        boolean admin = requestURI.contains("Admin");
        if (admin) {//如果是后台 就检验身份
            Integer admin1 = user1.getAdmin();
            if(admin1!=1){
                return Result.failed("你不是管理员");
            }
        }

        //成功
        // 第1步，先登录上
        StpUtil.login(user1.getUserId());
        // 第2步，获取 Token  相关参数
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        UserDTO userDTO = new UserDTO();
        BeanUtil.copyProperties(tokenInfo,userDTO);
        BeanUtil.copyProperties(user1,userDTO);

        // 第3步，返回给前端
        return Result.ok().addData(userDTO);
    }

    @Override
    public Result info(String token) {
        String loginIdByToken =(String) StpUtil.getLoginIdByToken(token);

        if(loginIdByToken==null){
            return Result.failed();
        }
        //通过id查询数据库
        int tokenId = Integer.parseInt(loginIdByToken);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_id",tokenId);
        User user = baseMapper.selectOne(userQueryWrapper);
        String ad;
        if(user.getAdmin()==1){
            ad="[admin]";
        }else{
            ad="[user]";
        }

        return Result.ok().add("roles",ad)
                .add("name",user.getUsername())
                .add("avatar",user.getAvatar());
    }

    @Override
    public Result logout() {
        return Result.ok();
    }


    @Override
    public Result getlist() {
        List<User> users = baseMapper.selectList(null);
        return Result.ok().addData(users);
    }

    @Override
    public Result getListBytt(User user) {
        Integer admin = user.getAdmin();
        String username = user.getUsername();

        QueryWrapper<User> Wrapper = new QueryWrapper<>();
        if(admin!=null){
            if(admin != 2)
            Wrapper.eq("admin",admin);
        }
        if (StrUtil.isNotEmpty(username) ){
            Wrapper.eq("username",username);
        }
        List<User> users = baseMapper.selectList(Wrapper);
        return Result.ok().addData(users);

    }

    @Override
    public Result delete(String id) {
        String[] id1 = id.split("=");

        baseMapper.deleteById(id1[0]);
        return Result.ok();
    }

    @Override
    public boolean saveAndUpdata(User user) {

        //添加操作
        //密码加密
        String password = user.getPassword();
        if(StrUtil.isNotEmpty(password)){
            user.setPassword( SecureUtil.md5(password));
        }

        Integer userId = user.getUserId();
        if(userId!=null){
            //更新操作
            baseMapper.updateById(user);
            return true;
        }


        boolean save = this.save(user);
        return save? true:false;
    }

    @Override
    public Result getListByPage(Long current, Long limit) {

        //页码  条数
        Page<User> userPage = new Page<User>(current, limit);
        Page<User> userPage1 = baseMapper.selectPage(userPage, null);

        return Result.ok().addData(userPage1);
    }

//    @Override
//    public Result checkInfo(String token) {
//
//        String loginIdByToken =(String) StpUtil.getLoginIdByToken(token);
//
//        if(loginIdByToken==null){
//            return Result.failed("请登录");
//        }
//        //通过id查询数据库
//        int tokenId = Integer.parseInt(loginIdByToken);
//        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
//        userQueryWrapper.eq("user_id",tokenId);
//        User user = baseMapper.selectOne(userQueryWrapper);
//        return Result.ok().addData(user);
//    }
        @Override
        public Result checkInfo() {

            int tokenId = StpUtil.getLoginIdAsInt();
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_id",tokenId);
            User user = baseMapper.selectOne(userQueryWrapper);
            return Result.ok().addData(user);
        }

    @Override
    public Result loginOut() {


        log.info("\n============{}",StpUtil.getTokenValue());
        // 当前会话注销登录
        StpUtil.logout();
        redisTemplate.delete("satoken:login:token:"+StpUtil.getTokenValue());
        log.info("\n============当前会话注销登录");
        return Result.ok().addData(Result.ok());
    }

    @Override
    public Result checkEmail(String email) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email",email);
        User user = baseMapper.selectOne(userQueryWrapper);

        if(user==null){
            return Result.ok().addData(Result.ok());
        }
        return Result.failed("邮箱已存在!");
    }

    @Override
    public Result checkUseName(String username) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",username);
        User user = baseMapper.selectOne(userQueryWrapper);
        log.info("\n============={}",user);

        if(user == null ){
            return  Result.ok().addData(Result.ok());
        }
        return Result.failed("昵称已存在!");
    }


}
